package com.environment_pro.monitor.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

public class StaticUtil {
	
	
	public static String null2String(String s){
		if (s != null ){
			return s;
		}else{
			return "";
		}
	}

	public static String null2String(Object attribute) {
		if (attribute != null ){
			return attribute.toString();
		}else{
			return "";
		}
	}

	public static int null2Integer(String parameter) {
		if (parameter != null ){
			return Integer.parseInt(parameter.toString());
		}else{
			return 0;
		}
	}
	
	public static Long null2Long(String parameter) {
		if (parameter != null ){
			return Long.parseLong(parameter.toString());
		}else{
			return 0L;
		}
	}
	
	public static Object getBean(String beanID){
		WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
		wac.getBean(beanID);
        return wac.getBean(beanID);//模块service
	}
	
	/**
	 * 从缓存中获取对象
	 * @param cachName
	 * @param key
	 * @return
	 */
	public static Object getCacheObject(String cachName,Object key){
		EhCacheCacheManager ehCacheCacheManager = (EhCacheCacheManager) getBean("cacheManager");
		Cache cache = ehCacheCacheManager.getCacheManager().getCache(cachName);
		Element element = cache.get(key);
        return element!=null?element.getObjectValue():null;
	}

	/**
	 * 将对象存入缓存
	 * @param cachName
	 * @param key
	 * @param value
	 */
	public static void putCacheObject(String cachName,Object key,Object value){
		EhCacheCacheManager ehCacheCacheManager = (EhCacheCacheManager) getBean("cacheManager");
		Cache cache = ehCacheCacheManager.getCacheManager().getCache(cachName);
		Element element = new Element(key, value);
		cache.put(element);
	}

	/**
	 * 日期类型转换成格式化字符串
	 * @param date
	 * @return
	 */
	public static String date2String(Date date) {
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return simpleDateFormat.format(date);
	}
	
	/**
	 * 日期格式化字符串转换成date
	 * @param date
	 * @return
	 * @throws ParseException 
	 */
	public static Date string2Date(String dateString) throws ParseException {
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return simpleDateFormat.parse(dateString);
	}
	
	/**
	 * 日期格式化字符串转换成date
	 * @param date
	 * @return
	 * @throws ParseException 
	 */
	public static String getDateString(int day,String pattern) {
		Date date = null;
		Calendar cd = Calendar.getInstance();
		cd.add(Calendar.DATE, day);
		date = cd.getTime();
		SimpleDateFormat dformat = new SimpleDateFormat(pattern);
		return dformat.format(date);
	}

}
